package com.itheima.security;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.service.UserService;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

//需要使用dubbo调用我们的UserService查询用户的权限信息 所以我们要使用包扫描 + 注解的方式
//包扫描注意需要使用dubbo的包扫描，spring的扫描是不能识别com.alibaba.dubbo.config.annotation.Reference
@Component
public class SpringSecurityUserService implements UserDetailsService {

    @Reference
    UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
//        根据用户名查询用户的基本信息（密码，用户的权限集合）
        com.itheima.pojo.User user = userService.loadUserByUsername(username);
        if(user == null){
            return null;
        }

        //需要把user转换为UserDetails
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        Set<Role> roles = user.getRoles();
            for (Role role : roles) {
                Set<Permission> permissions = role.getPermissions();
                for (Permission permission : permissions) {
                    authorities.add(new SimpleGrantedAuthority(permission.getKeyword()));
                }
            }

        return new org.springframework.security.core.userdetails.User(username,user.getPassword(),authorities);
    }
}
